﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Weazel.Willows.Model
{
	public partial class SignalOutConnector
		: SignalConnectorBase
	{
		private bool refined = false;

		private Weazel.Willows.RefinedModel.OutPort port;
		public Weazel.Willows.RefinedModel.OutPort Port
		{
			get { return port; }
		}

		public override void Refine(RefinedModel.Model model)
		{
			if (refined)
				return;

			refined = true;

			Module module = Parent as Module;
			Weazel.Willows.RefinedModel.Datapath datapath = module.Datapath;

			port = new Weazel.Willows.RefinedModel.OutPort(TypeRegistry, datapath, LocalName, Type);

			datapath.OutPorts.Add(LocalName, port);

			if (this.Input is Signal)
			{
				Weazel.Gezel.Model.Expression updateExpr =
					new Weazel.Gezel.Model.BinaryExpression(
						Weazel.Gezel.Model.ExpressionType.Assignment,
						new Weazel.Gezel.Model.LeafExpression(Weazel.Gezel.Model.ExpressionType.Identifier, LocalName),
						new Weazel.Gezel.Model.LeafExpression(Weazel.Gezel.Model.ExpressionType.Identifier, Input.LocalName)
					);

				datapath.SignalFlowGraphs["always"].Expressions.Add(updateExpr);
			}

			this.Input.Refine(model);
			this.Output.Refine(model);
		}
	}
}
